import router from '@/router'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import settings from './settings'
import store from './store'
import { getUserMenuList } from '@/api/user'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/consultation', '/404'] // no redirect whitelist

// 匹配权限路由
function judeAuth(to: any, next: Function, authList: any[], isFirst = true) {
  if (authList && authList.length && to.path === '/') {
    next(authList[0].path)
    return
  }
  if (
    authList.some((auth: any) => {
      if (auth.path === to.path) {
        return true
      }
      if (auth.children && auth.children.length) {
        if (judeAuth(to, next, auth.children, false)) {
          return true
        }
      } else {
        return false
      }
    })
  ) {
    next()
    return true
  } else {
    if (isFirst) {
      Message.error('没有权限')
      NProgress.done()
    }
    return false
  }
}
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  // 无论是否登录都能进
  if (whiteList.indexOf(to.path) !== -1) {
    document.title = to.meta.title || settings.title
    next()
    return
  }
  // determine whether the user has logged in
  const hasToken = localStorage.getItem('token')
  if (hasToken) {
    // 已经请求回权限数据
    if (store.state.user.authorities) {
      // 检验权限
      judeAuth(to, next, store.state.user.authorities)
    } else {
      // 未请求回权限数据进行请求
      getUserMenuList().then((res: any) => {
        if (res.code === 200) {
          store.commit('user/SET_AUTHORITIES', res.data)
          // 检验权限
          judeAuth(to, next, store.state.user.authorities)
        }
      })
    }
  } else {
    /* has no token*/
    next(`/login`)
    NProgress.done()
  }
})

router.afterEach((to: any) => {
  // finish progress bar
  document.title = to.meta.title || settings.title
  NProgress.done()
})
